package com.dili.dd.gpi.controller;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dili.dd.gpi.domain.GciSnapshot;
import com.dili.dd.gpi.enums.ApplyType;
import com.dili.dd.gpi.enums.GCIType;
import com.dili.dd.gpi.exception.BusinessException;
import com.dili.dd.gpi.service.GciSnapshotService;
import com.dili.dd.gpi.util.AcceptHashMap;
import com.dili.dd.gpi.util.ExportExcelUtil;
import com.dili.dd.gpi.util.Pagination;
import com.dili.dd.gpi.util.StringUtils;
import com.dili.dd.gpi.util.spring.HttpParameterParser;
import com.dili.dd.gpi.util.spring.JsonView;
import com.dili.dd.gpi.util.spring.ObjectConvertAnno;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.*;

/**
 * Created by zhaoYuan on 2015/3/25.
 */
@Controller
@RequestMapping("/gci")
public class GciController {

    private static final Logger logger = LoggerFactory.getLogger(GciController.class);

    @Resource
    private GciSnapshotService gciSnapshotService;

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String toList(){
        return "/WEB-INF/views/gci/list";
    }

    @RequestMapping(value = "/save.htm",method = RequestMethod.GET)
    public String toSave(){
        return "/WEB-INF/views/gci/add";
    }

    @RequestMapping(value = "/save.htm",method = RequestMethod.PUT)
    public String save(GciSnapshot gci,Model model){
        String title = gci.getTitle();
        List<String> splits = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(title);
        Set<String> titles = new LinkedHashSet<>(splits);

        String describe = gci.getDescribe();
        List<String> describes = Splitter.on("\n").trimResults().splitToList(describe);

        List<GciSnapshot> exists = new LinkedList<>();
        List<GciSnapshot> news = new LinkedList<>();
        try {
            boolean apply = gciSnapshotService.apply(titles, gci.getType(), gci.getPrefix(), gci.getSuffix(),
                    describes, exists,news, ApplyType.PAGE);
            Map<String,List<GciSnapshot>> data = new HashMap<>();
            data.put("exists",exists);
            data.put("news",news);
            model.addAttribute("success", apply);
            model.addAttribute("data", data);
        } catch (BusinessException e) {
            model.addAttribute("success", false);
            model.addAttribute("message", e.getMessage());
        }
        return "/WEB-INF/views/gci/result";
    }


    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ModelAndView list(@ObjectConvertAnno HttpParameterParser parser,
                             @ObjectConvertAnno Pagination pagination){
        logger.info("获取gci列表");
        String key = parser.getString("sSearch");

        //构造查询参数
        AcceptHashMap<String,Object> params =  AcceptHashMap.newInstance();
        params.acceptIf("key", "%" + key + "%", !StringUtils.isNullOrEmpty(key));
        params.accept("deleted",Boolean.FALSE);
        List<GciSnapshot> gciSnapshots = gciSnapshotService.find(params, pagination);

        Map<String,Object> model = new HashMap<>();
            model.put("pagination",pagination);
        model.put("data",gciSnapshots);
        model.put("sEcho",parser.getString("sEcho"));
        return new ModelAndView(new JsonView(model, SerializerFeature.WriteMapNullValue));
    }

    @RequestMapping(value = "/check",method = RequestMethod.GET)
    public ModelAndView check(GCIType type,String title){
        List<String> titles = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(title);
        List<GciSnapshot> gs = gciSnapshotService.isExist(titles, type);
        boolean success = false;
        List<String> exists =new LinkedList<>();
        if(gs != null && !gs.isEmpty()){
            success = false;
            for (GciSnapshot g : gs) {
                exists.add(g.getTitle());
            }
        }else{
            success = true;
        }
        return new ModelAndView(new JsonView(success, Joiner.on(",").join(exists)));
    }

    @RequestMapping(value = "/download.htm")
    public void downloadMemberTemplate(HttpServletResponse response){
        String fileName = MessageFormat.format("内容标注对照表{0,date,yyyyMMdd}.xls", new Date());
        String sheetName = "内容标注对照表";
        Map<String,String> columnMap = new LinkedHashMap<>();
        columnMap.put("title","标题");
        columnMap.put("gci","标注值");
        columnMap.put("type","层级");
        columnMap.put("prefix","前缀");
        columnMap.put("suffix","后缀");
        columnMap.put("describe","描述");
        Map<String,Object> params = new HashMap<>();
        params.put("deleted",Boolean.FALSE);
        List<GciSnapshot> gpiSnapshots = gciSnapshotService.find(params, null);
        ExportExcelUtil.exportExcel(response, fileName, gpiSnapshots, sheetName, columnMap);
    }
}
